package com.text.mqtt_text.service.impl;

import com.text.mqtt_text.mqtt.Set;
import com.text.mqtt_text.service.StatusService;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


@Slf4j
@Service
public class StatusServiceImpl implements StatusService {

    private static final String BASE_URL = "https://xiaozhi.me";
    private static final String AUTH_TOKEN = "Bearer eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjIyODUzOCwidXNlcm5hbWUiOiIrODYxMzI3MzA1NzI1MyIsInRlbGVwaG9uZSI6Iis4NjEzMioqKio3MjUzIiwicm9sZSI6InVzZXIiLCJpYXQiOjE3NDU2Nzk4MTQsImV4cCI6MTc1MzQ1NTgxNH0.V8lViEN_xo0D2Kj40zHJNLnsHgShwpugY5cKdv6OeCvf_7-DceD_i4RiVWMI2ZXIhsXFFwcwWsXWDGShVI1Itg"; // 替换为实际的Token

    @Override
    public Boolean getStatus() {

        // 设置输出目录为当前目录下的 downloaded_configs 文件夹
        String outputDir = "downloaded_configs";

        // 指定 agent ID
        String agentId = "170573"; // 您指定的agent ID

        try {
            // 创建输出目录（如果不存在）
            Path outputPath = Paths.get(outputDir);
            if (!Files.exists(outputPath)) {
                Files.createDirectories(outputPath);
            }

            // 构建请求 URL
            String url = BASE_URL + "/api/agents/" + agentId;
            log.info("正在获取 agent {} 的配置内容...", agentId);
            log.info("请求 URL: {}", url);

            // 发送 GET 请求
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Authorization", AUTH_TOKEN);

            int responseCode = connection.getResponseCode();

            log.info("响应状态码: {}", responseCode);

            if (responseCode == 200) {
                // 读取响应内容
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 解析 JSON 响应
                JSONObject jsonResponse = new JSONObject(response.toString());
                if (!jsonResponse.getBoolean("success")) {
                    log.info("API 返回错误: {}", jsonResponse.getString("message"));
                    return false;
                }

                // 获取 memory 字段内容
                JSONObject data = jsonResponse.getJSONObject("data").getJSONObject("agent");
                String memoryContent = data.optString("memory", "");
                if (memoryContent.isEmpty()) {
                    log.info("未找到 memory 内容");
                    return false;
                }

                // 保存到文件
                String fileName = "memory.txt";
                Path filePath = Paths.get(outputDir, fileName);
                Files.write(filePath, memoryContent.getBytes("UTF-8"));
                log.info("memory 内容已保存到: {}", filePath);
                log.info("内容长度: {} 字符", memoryContent.length());
                return true;
            } else {
                log.info("请求失败，状态码: {}", responseCode);

                return false;
            }
        } catch (Exception e) {
            log.info("处理过程中出错: {}", e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    public static com.aliyun.iot20180120.Client createClient() throws Exception {
        // 工程代码建议使用更安全的无AK方式，凭据配置方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.credentials.Client credential = new com.aliyun.credentials.Client();

        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setCredential(credential);
        // Endpoint 请参考 https://api.aliyun.com/product/Iot
        config.endpoint = "iot.cn-shanghai.aliyuncs.com";
        return new com.aliyun.iot20180120.Client(config);
    }

    /**
     * 爬虫
     *
     * @throws Exception
     */
    @Override
    public void send() throws Exception {

        Set.main(new String[0]);
    }
}
    /**
     * 百度AI分析
     * @param data
     * @return
     */
//    public static final String API_KEY = "yfcFVbmxdf5YbKLzN6kBL8AK";
//    public static final String SECRET_KEY = "DN57SLClq1tNXZeyLoUmwdcEW3GOhsK6";
//    public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().readTimeout(300, TimeUnit.SECONDS).build();
//
//    @Override
//    public Status AIThink(String data) throws IOException {
//        MediaType mediaType = MediaType.parse("application/json");
//        RequestBody body = RequestBody.create(mediaType, "{\"text\":\" "+data+" \"}");
//        Request request = new Request.Builder()
//                .url("https://aip.baidubce.com/rpc/2.0/nlp/v1/sentiment_classify?charset=UTF-8&access_token=" + getAccessToken())
//                .method("POST", body)
//                .addHeader("Content-Type", "application/json")
//                .addHeader("Accept", "application/json")
//                .addHeader("Authorization", "Bearer")
//                .build();
//        Response response = HTTP_CLIENT.newCall(request).execute();
//
//        //用String类型接收json的数据
//        String message = response.body().string();
//        //新建status类，用来接收每个数据
//        Status status = new Status();
//        //json格式的数据转成纯文本
//        try {
//            ObjectMapper objectMapper = new ObjectMapper();
//            Map<String, Object> jsonMap = objectMapper.readValue(message, Map.class);
//
//            String text = (String) jsonMap.get("text");
//            status.setStatus(text);
//
//            //将接口的json数据改成status
//            java.util.List<Map<String, Object>> items = (java.util.List<Map<String, Object>>) jsonMap.get("items");
//            if (items != null && !items.isEmpty()) {
//                Map<String, Object> item = items.get(0);
//                status.setSentiment(String.valueOf(item.get("sentiment")));
//                status.setConfidence(String.valueOf(item.get("confidence")));
//                status.setPositive_prob(String.valueOf(item.get("positive_prob")));
//                status.setNegative_prob(String.valueOf(item.get("negative_prob")));
//
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        return status;
//    }

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
//    static String getAccessToken() throws IOException {
//        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
//        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
//                + "&client_secret=" + SECRET_KEY);
//        Request request = new Request.Builder()
//                .url("https://aip.baidubce.com/oauth/2.0/token")
//                .method("POST", body)
//                .addHeader("Content-Type", "application/x-www-form-urlencoded")
//                .build();
//        Response response = HTTP_CLIENT.newCall(request).execute();
//        return new JSONObject(response.body().string()).getString("access_token");
//    }
//
//}
